package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConst;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.Role;
import com.itheima.pojo.SysUser;
import com.itheima.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpSession;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

	@Reference
	private UserService userService;
	/**
	 * 获取用户名
	 * @return
	 */
	@RequestMapping("/getUsername")
	public Result getUsername(HttpSession session){
		//session.getAttribute("SPRING_SECURITY_CONTEXT");
		//session.getAttributeNames();  //可以获取session中所有的参数名
		//SecurityContextHolder 帮助类， 可以直接获取 session中 securityContext对象
		// SecurityContext: 上下文对象, 包含了用户信息和权限信息
		SecurityContext context = SecurityContextHolder.getContext();
		//获取认证对象
		Authentication authentication = context.getAuthentication();
		//获取principal 对象
		Object principal = authentication.getPrincipal();
		//如果 没有登录，获取到的是匿名用户，如果的登录了获取到的User对象
		//instanceof : 实例类型判断运算符
		String username = null;
		if(principal instanceof User){
			User u = (User) principal;
			username = u.getUsername();
		}
		log.debug("获取到的用户名为：" + username);
		return new Result(true, MessageConst.GET_USERNAME_SUCCESS, username);
	}

	/**
	 * 登录成功后访问的方法
	 * 	登录成功以后： pages/main.html
	 */
	@RequestMapping("/loginSuccess")
	public ModelAndView loginSuccess(){
		log.debug("登录成功!!");
		//在ModelAndView 中指定视图名称
		//默认为请求转发
		// 设置为重定向
		return new ModelAndView("redirect:http://localhost:83/pages/main.html");
	}

	/**
	 * 登录失败后访问的方法
	 * 登录失败以后：跳转到登录页面, 重新登录, 提示登录失败
	 */
	@RequestMapping("/loginFail")
	public ModelAndView loginFail(){
		log.debug("登录失败!!");
		return new ModelAndView("redirect:http://localhost:83/login.html");
	}


	@RequestMapping("/getShowMenu")
	public Result getShowMenu() {
		SecurityContext context = SecurityContextHolder.getContext();
		//获取认证对象
		Authentication authentication = context.getAuthentication();
		//获取principal 对象
		Object principal = authentication.getPrincipal();
		//如果 没有登录，获取到的是匿名用户，如果的登录了获取到的User对象
		//instanceof : 实例类型判断运算符
		String username = null;
		if(principal instanceof User){
			User u = (User) principal;
			username = u.getUsername();
		}
		log.debug("获取到的用户名为：" + username);
		List<Map<String,Object>> menuList = userService.getShowMenu(username);
		return new Result(true, MessageConst.GET_MENU_SUCCESS, menuList);
	}


	@RequestMapping("/add")
	@PreAuthorize("hasAuthority('ROLE_ADMIN')")
	public Result add(@RequestBody SysUser sysUser, Integer[] roleIds){
		log.debug("UserController:add : sysUser:" +sysUser);
		log.debug("UserController:add : roleIds: " +roleIds);
		userService.add(sysUser,roleIds);
		log.debug("用户数据添加成功！！");
		return new Result(true, MessageConst.ADD_USER_SUCCESS);
	}

	/**
	 * 分页查询
	 *  1.调用Service获取分页结果数据
	 * @param queryPageBean
	 * @return
	 */
	@PreAuthorize("hasAuthority('ROLE_ADMIN')")
	@RequestMapping("/findPage")
	public Result findPage(@RequestBody QueryPageBean queryPageBean){
		log.debug("UserController{"+queryPageBean+"}");
		PageResult pageResult = userService.findPage(queryPageBean);
		log.debug("权限数据分页查询成功!!");
		return new Result(true, MessageConst.QUERY_USER_SUCCESS, pageResult);
	}

	@RequestMapping("/findById")
	@PreAuthorize("hasAuthority('ROLE_ADMIN')")
	public Result findById(Integer id){
		log.debug("PermissionController：findById:" + id);
		SysUser sysUser = userService.findById(id);
		log.debug("根据id查询权限数据成功!!");
		return new Result(true, MessageConst.QUERY_USER_SUCCESS, sysUser);
	}

	@RequestMapping("/findroleIdsById")
	public Result findroleIdsById(Integer id){
		log.debug("UserController:findroleIdsById: " + id);
		List<Integer> roleIds = userService.findroleIdsById(id);
		log.debug("根据用户id查询角色id成功!!");
		return new Result(true, MessageConst.QUERY_CHECKGROUP_SUCCESS,roleIds);
	}

	@RequestMapping("/edit")
	@PreAuthorize("hasAuthority('ROLE_ADMIN')")
	public Result edit(Integer[] roleIds,@RequestBody SysUser sysUser){
		log.debug("PermissionController:edit: " + Arrays.toString(roleIds));
		log.debug("PermissionController:edit: " + sysUser);
		userService.edit(sysUser,roleIds);
		log.debug("权限数据修改成功!!");
		return new Result(true, MessageConst.EDIT_USER_SUCCESS);
	}

	@RequestMapping("/findAll")
	@PreAuthorize("hasAuthority('ROLE_ADMIN')")
	public Result findAll(){
		log.debug("UserController:findAll:");
		List<Role> userList = userService.findAll();
		log.debug("用户数据查询成功！！！");
		return new Result(true,MessageConst.QUERY_USER_SUCCESS, userList);
	}

	@RequestMapping("/delById")
	public Result delById(Integer id) {
		log.debug("delById:" + id);
		userService.delById(id);
		log.debug("删除用户数据成功");
		return new Result(true, MessageConst.DELETE_USER_SUCCESS);
	}
}